package com.ihrm.common.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * @author
 * @version V1.0
 * @Package com.ihrm.common.config
 * @date 2021/1/9 15:41
 * @Copyright © 2020-2021
 * Feign微服务调用组件配置类
 */
@Configuration
public class FeignConfig {
    /**
     * 通过feign调用其他微服务时复制请求头信息
     */
    @Bean
    public RequestInterceptor requestInterceptor() {
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate requestTemplate) {
                //获取请求参数
                ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                if (attributes != null) {
                    //获取请求request
                    HttpServletRequest request = attributes.getRequest();
                    Enumeration<String> headerNames = request.getHeaderNames();
                    if (headerNames != null) {
                        while (headerNames.hasMoreElements()) {
                            //获取请求头名称
                            String name = headerNames.nextElement();
                            //获取请求头的值
                            String value = request.getHeader(name);
                            //添加请求头到feign中
                            requestTemplate.header(name, value);
                        }
                    }
                }
            }
        };
    }
}
